package com.allm.ai.api.controller;

import com.allm.ai.common.entity.AiModel;
import com.allm.ai.common.entity.ModelTag;
import com.allm.ai.common.service.AiModelService;
import com.allm.ai.common.service.AiModelTagService;
import com.allm.ai.common.service.ModelTagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * AI模型管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/ai-models")
@RequiredArgsConstructor
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, allowCredentials = "false")
public class AiModelController {

    private final AiModelService aiModelService;
    private final AiModelTagService aiModelTagService;
    private final ModelTagService modelTagService;

    /**
     * 根据ID获取AI模型
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getAiModelById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            return aiModelService.findById(id)
                    .map(model -> {
                        response.put("success", true);
                        response.put("data", model);
                        return ResponseEntity.ok(response);
                    })
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取AI模型失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "获取AI模型失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除AI模型
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteAiModel(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            aiModelService.deleteById(id);
            response.put("success", true);
            response.put("message", "AI模型删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("删除AI模型失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "删除AI模型失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 启用/禁用AI模型
     */
    @PatchMapping("/{id}/toggle-active")
    public ResponseEntity<Map<String, Object>> toggleAiModelActive(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            AiModel model = aiModelService.toggleActive(id);
            response.put("success", true);
            response.put("message", "AI模型状态切换成功");
            response.put("data", model);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("切换AI模型状态失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "切换AI模型状态失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

        /**
     * 获取所有启用的AI模型 - 按标签分组
     */
    @GetMapping("/active")
    public ResponseEntity<Map<String, Object>> getActiveAiModels() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 获取所有启用的模型
            List<AiModel> models = aiModelService.findActiveModels();
            
            // 获取所有启用的标签，按排序字段排序
            List<ModelTag> allTags = modelTagService.getAllActiveTags();
            
            // 按标签分组模型
            Map<String, Object> groupedModels = groupModelsByTags(models, allTags);
            
            response.put("success", true);
            response.put("data", groupedModels);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取启用AI模型失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "获取AI模型失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }


    /**
     * 按标签分组模型
     */
    private Map<String, Object> groupModelsByTags(List<AiModel> models, List<ModelTag> allTags) {
        Map<String, Object> result = new HashMap<>();
        
        // 为每个模型添加标签信息
        List<Map<String, Object>> modelsWithTags = models.stream()
                .map(model -> {
                    Map<String, Object> modelMap = new HashMap<>();
                    modelMap.put("id", model.getId());
                    modelMap.put("name", model.getName());
                    modelMap.put("displayName", model.getDisplayName());
                    modelMap.put("icon", model.getIcon());
                    modelMap.put("iconClass", model.getIconClass());
                    modelMap.put("colorClass", model.getColorClass());
                    modelMap.put("modelKey", model.getName());
                    modelMap.put("isFree", model.getIsFree());
                    modelMap.put("modelDescription", model.getModelDescription());
                    modelMap.put("rankPosition", model.getRankPosition());
                    modelMap.put("flowersCount", model.getFlowersCount());
                    modelMap.put("eggsCount", model.getEggsCount());
                    modelMap.put("popularityScore", model.getPopularityScore());
                    modelMap.put("discussionsCount", model.getDiscussionsCount());
                    modelMap.put("responseSpeedScore", model.getResponseSpeedScore());
                    modelMap.put("accuracyScore", model.getAccuracyScore());
                    modelMap.put("copywritingScore", model.getCopywritingScore());
                    modelMap.put("drawingScore", model.getDrawingScore());
                    modelMap.put("programmingScore", model.getProgrammingScore());
                    
                    // 获取模型的标签
                    List<ModelTag> modelTags = aiModelTagService.getModelTags(model.getId());
                    modelMap.put("tags", modelTags);
                    
                    return modelMap;
                })
                .collect(Collectors.toList());
        
        // 按标签分组
        Map<String, List<Map<String, Object>>> groupedByTags = new LinkedHashMap<>();
        
        // 为每个标签创建分组
        for (ModelTag tag : allTags) {
            List<Map<String, Object>> tagModels = modelsWithTags.stream()
                    .filter(modelMap -> {
                        @SuppressWarnings("unchecked")
                        List<ModelTag> modelTags = (List<ModelTag>) modelMap.get("tags");
                        return modelTags.stream()
                                .anyMatch(modelTag -> modelTag.getId().equals(tag.getId()));
                    })
                    .collect(Collectors.toList());
            
            if (!tagModels.isEmpty()) {
                groupedByTags.put(tag.getTag(), tagModels);
            }
        }
        
        // 添加未分组的模型（没有标签的模型）
        List<Map<String, Object>> ungroupedModels = modelsWithTags.stream()
                .filter(modelMap -> {
                    @SuppressWarnings("unchecked")
                    List<ModelTag> modelTags = (List<ModelTag>) modelMap.get("tags");
                    return modelTags.isEmpty();
                })
                .collect(Collectors.toList());
        
        if (!ungroupedModels.isEmpty()) {
            groupedByTags.put("其他", ungroupedModels);
        }
        
        // 构建返回结果
        result.put("groupedModels", groupedByTags);
        result.put("allModels", modelsWithTags);
        result.put("tags", allTags);
        
        // 添加统计信息
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalModels", models.size());
        statistics.put("totalTags", allTags.size());
        statistics.put("tagGroups", groupedByTags.size());
        result.put("statistics", statistics);
        
        return result;
    }

    /**
     * 根据标签获取AI模型
     */
    @GetMapping("/by-tag/{tagName}")
    public ResponseEntity<Map<String, Object>> getAiModelsByTag(@PathVariable String tagName) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 根据标签名称查找标签
            Optional<ModelTag> tagOpt = modelTagService.getTagByName(tagName);
            if (tagOpt.isEmpty()) {
                response.put("success", false);
                response.put("message", "标签不存在: " + tagName);
                return ResponseEntity.ok(response);
            }
            
            ModelTag tag = tagOpt.get();
            
            // 获取该标签下的所有启用的模型ID
            List<Long> modelIds = aiModelTagService.getActiveModelIdsByTagId(tag.getId());
            
            // 获取模型详细信息
            List<AiModel> models = modelIds.stream()
                    .map(modelId -> aiModelService.findById(modelId))
                    .filter(Optional::isPresent)
                    .map(Optional::get)
                    .filter(AiModel::getIsActive)
                    .collect(Collectors.toList());
            
            response.put("success", true);
            response.put("data", Map.of(
                "tag", tag,
                "models", models,
                "count", models.size()
            ));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("根据标签获取AI模型失败: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", "获取AI模型失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
} 